//
//  OpenSDK_UIUtil.m
//  OpenSDK
//
//  Created by 涂俊 on 2018/2/1.
//  Copyright © 2018年 WYHT. All rights reserved.
//

#import "OpenSDK_UIUtil.h"
#import <UIKit/UIKit.h>

@implementation OpenSDK_UIUtil


+ (UIWindow *)getCurrentWindow {
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal) {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows) {
            if (tmpWin.windowLevel == UIWindowLevelNormal) {
                window = tmpWin;
                break;
            }
        }
    }
    return window;
}

+ (UIViewController *)getCurrentVC {
    UIViewController *result = nil;
    UIWindow * window = [self getCurrentWindow];
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]]) {
        result = nextResponder;
    } else {
        result = window.rootViewController;
    }
    
    return result;
}

+ (UIViewController *)currentViewController {
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    UIViewController *vc = keyWindow.rootViewController;
    while (vc.presentedViewController) {
        vc = vc.presentedViewController;

        if ([vc isKindOfClass:[UINavigationController class]]) {
            vc = [(UINavigationController *)vc visibleViewController];
        } else if ([vc isKindOfClass:[UITabBarController class]]) {
            vc = [(UITabBarController *)vc selectedViewController];
        }
    }
    return vc;
}

//获取第一个parentViewController。如果没有，返回传入VC
+ (UIViewController *)getFirstParentVC:(UIViewController *)vc {
    UIViewController *result = vc;
    while (result.parentViewController != nil) {
        result = result.parentViewController;
    }
    return result;
}

+ (CGFloat)getSystemScale {
    CGFloat scale_screen = [UIScreen mainScreen].scale;
    //不支持iphone3GS的情况
    if (scale_screen==1) {
        scale_screen=2;
    }
    //使用iphone4s的宽度为基准值
    CGFloat baseValue=320;
    int baseScale=2;
    CGRect rx = [UIScreen mainScreen].bounds;
    CGFloat width=rx.size.width;
    CGFloat height=rx.size.height;
    
    //处理iphone6 plus的情况，奇葩的分辨率
    if(scale_screen==3&&((width==414&&height==736)||(width==736&&height==414)))
        scale_screen=2.46;
    //计算缩放比例
    CGFloat v=(height>width?width:height)/baseValue;
    //不支持iphone3GS的情况
    if (v<1) {
        v=1;
    }
    
    v = v*(scale_screen/baseScale);
    return 1.0 / scale_screen * v;
}

//ios的坐标系统只识别point，需要转换为像素
+ (CGFloat)getUISize:(CGFloat)value {
    return value * [self getSystemScale];
}

@end
